﻿using AutoMapper;
using B.S.Domain.Generateplan;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.Data.MES.API.Applications.GenerateItemsApplication
{
    /// <summary>
    /// 添加生产计划物品处理器
    /// </summary>
    public class AddGenerateItemsCommandHorter : IRequestHandler<AddGenerateItemsCommand, APIRequst<int>>
    {
        private readonly IBaseRepository<GenerateItems> _repository;
        private readonly IMapper _mapper;

        public AddGenerateItemsCommandHorter(IBaseRepository<GenerateItems> repository, IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }

        public async Task<APIRequst<int>> Handle(AddGenerateItemsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 检查物品编号是否已存在
                var existingItem = await _repository.GetAll()
                    .Where(x => x.ItemNumber == request.ItemNumber && x.IsDel == false)
                    .FirstOrDefaultAsync(cancellationToken);

                if (existingItem != null)
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.失败,
                        Msg = "物品编号已存在",
                        Data = 0
                    };
                }

                // 创建新的物品实体
                var generateItem = new GenerateItems
                {
                    ItemNumber = request.ItemNumber,
                    ItemName = request.ItemName,
                    SpecificationModel = request.SpecificationModel,
                    Unit = request.Unit,
                    ItemCategory = request.ItemCategory,
                    ItemClassification = request.ItemClassification,
                    Brand = request.Brand,
                    OrderName = request.OrderName,
                    GenerateplanBasicId = request.GenerateplanBasicId,
                    IsDel = false
                };

                // 添加到数据库
                await _repository.Add(generateItem);

                return new APIRequst<int>
                {
                    Code = RequstCode.成功,
                    Msg = "添加成功",
                    Data = generateItem.GenerateItemsId
                };
            }
            catch (Exception ex)
            {
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"添加失败：{ex.Message}",
                    Data = 0
                };
            }
        }
    }
}
